<script setup lang="ts">
import {computed, ref, watch} from "vue";
import {graphic} from "echarts/core";
import {cloneDeep} from "lodash-es";
import {timeFormat} from "@/utils";
import {Vue3AutoScroll} from "vue3-auto-scroll";
import "vue3-auto-scroll/dist/style.css";
import DateTimePicker from '@/components/date-time-picker/index.vue'
import {getTodayStartTimestamp} from "@/components/date-time-picker/timeUtils";

const props = defineProps({
  data:{
    type:Object,
    default(){
      return {}
    }
  }
})

const emits = defineEmits(['updateTime'])

const visible = ref(false)

const categories = ['深度睡眠', '浅度睡眠', '快速眼动','清醒时间'];
const categoriesConfig = ['','清醒时间','快速眼动','浅度睡眠', '深度睡眠']
const types = [
  {name: '深度睡眠', color: '#3634A9'},
  {name: '浅度睡眠', color: '#007CFF'},
  {name: '快速眼动', color: '#00B0EC'},
  {name: '清醒时间', color: '#FF7963'},
];

const nowDate = ref(getTodayStartTimestamp() - 86400000)

const option = ref({});
const smfxOption = ref({});

const renderItem = (params:any, api:any) => {
  let categoryIndex = api.value(0);
  let start = api.coord([api.value(1), categoryIndex]);
  let end = api.coord([api.value(2), categoryIndex]);
  let height = api.size([0, 1])[1] * 1;

  let rectShape = graphic.clipRectByRect({
    x: start[0],
    y: start[1] - height / 2,
    width: end[0] - start[0],
    height: height
  }, {
    x: params.coordSys.x,
    y: params.coordSys.y,
    width: params.coordSys.width,
    height: params.coordSys.height
  });

  return rectShape && {
    type: 'rect',
    shape: rectShape,
    style: api.style()
  };
}

const legendData = ref(['清醒时间','快速眼动','浅度睡眠','深度睡眠'])
const legendDataValue = ref([50,10,20,20])
const setOption = async (sData:any[],data:any, startAngle:any) => {
  option.value = {
    tooltip: {
      formatter: function (params:any) {
        return params.marker + params.name + ': ' + `${params.data.begin}-${params.data.end}`;
      }
    },
    title: {
      show:false
    },
    grid: {
      top:0,
      left:60,
      right:0,
      bottom:20,
    },
    xAxis: {
      scale: true,
      axisLabel: {
        formatter: function (val:any,index:number) {
          return index % 2 === 0 ? timeFormat(val * 1000,'hh:MM') : '';
        }
      }
    },
    yAxis: {
      axisLine:{
        show:false
      },
      axisTick:{
        show:false
      },
      data: categories
    },
    series: [{
      type: 'custom',
      renderItem: renderItem,
      encode: {
        x: [1, 2],
        y: 0
      },
      data: sData
    }]
  };
  legendDataValue.value = [data.sober || 0,data.eye || 0,data.shallow || 0,data.deep || 0]
  smfxOption.value = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top:'center',
      right: '0',
      orient: 'vertical',
      icon: 'circle',
      textStyle:{
        color:'#1A1A1A',
      },
      data: legendData.value,
      formatter:(name:any)=>{
        return name
      }
    },
    series: [
      {
        color:['#FF7963','#00B0EC','#007CFF','#3634A9'],
        type: 'pie',
        startAngle: startAngle,
        animation:false,
        clockWise: false,
        hoverAnimation:false,
        radius: ['80%', '90%'],
        center:[60, '50%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 5
        },
        label: {
          show: false,
          position: 'center'
        },
        labelLine: {
          show: false
        },
        data: [
          { value: legendDataValue.value[0], name: '清醒时间' },
          { value: legendDataValue.value[1], name: '快速眼动' },
          { value: legendDataValue.value[2], name: '浅度睡眠' },
          {
            value: legendDataValue.value[3],
            name: '深度睡眠',
            label: {
              normal: {
                rich: {
                  a: {
                    color: '#1A1A1A',
                    align: 'center',
                    fontSize: 18,
                    fontWeight: "bold"
                  },
                  c: {
                    color: '#1A1A1A',
                    align: 'center',
                    fontSize: 12,
                    fontWeight: "bold"
                  },
                  b: {
                    color: '#4D4D4D',
                    align: 'center',
                    fontSize: 12
                  }
                },
                formatter: function(params:any){
                  return "{a|"+(params.value || 0)+"}"+"{c|%}"+"\n\n{b|深度睡眠}";
                },
                position: 'center',
                show: true,
                textStyle: {
                  fontSize: '14',
                  fontWeight: 'normal',
                  color: '#fff'
                }
              }
            },
          }
        ]
      },
      {
        name: '统计',
        type: 'gauge',
        splitNumber: 30, //刻度数量
        min: 0,
        max: 100,
        radius: '110%', //图表尺寸
        center:[60, '50%'],
        startAngle: 90,
        endAngle: -269.9999,
        axisLine: {
          show: false,
        },
        legend:{
          show:false,
        },
        axisTick: {
          show: true,
          lineStyle: {
            color: '#0dc2fe',
            width: 0
          },
          length: 0,
          splitNumber: 1
        },
        splitLine: {
          show: true,
          length: 5,
          lineStyle: {
            color: '#FEEAE8',
          }
        },
        axisLabel: {
          show: false
        },
        pointer: { //仪表盘指针
          show: 0,
        }
      },
    ]
  };
};

const setData = (data:any[]):any[] => {
  const beginDate = ref(nowDate.value)
  const endDate = ref(nowDate.value)
  const sData:any[] = []
  data?.map((v:any) => {
    const begin = new Date(beginDate.value)
    begin.setHours(v.begin.split(':')[0])
    begin.setMinutes(v.begin.split(':')[1])
    let end = new Date(endDate.value)
    end.setHours(v.end.split(':')[0])
    end.setMinutes(v.end.split(':')[1])
    const typeItem:any = types.find((type:any) => type.name == categoriesConfig[v.type]) || {}
    if(+end - +begin < 0){
      endDate.value += 86400000
      beginDate.value += 86400000
      end = new Date(endDate.value)
      end.setHours(v.end.split(':')[0])
      end.setMinutes(v.end.split(':')[1])
    }

    sData.push({
      ...v,
      name: categoriesConfig[v.type],
      value: [
        categories.indexOf(categoriesConfig[v.type]),
        +begin / 1000,
        +end / 1000,
        v
      ],
      itemStyle: {
        normal: {
          color: typeItem.color
        }
      }
    })
  })

  return sData
}

watch(()=>props.data, (newval:any)=>{
  const val = cloneDeep(newval)
  setOption([],val,0)
  setOption(setData(val.sleepList),val,0)
},{
  deep:true,
  immediate:true
})


watch(()=>nowDate.value,(v)=>{
  visible.value = false
  emits('updateTime', v)
},{
  immediate:true,
  deep:true
})

const minutesToHoursAndMinutes = (ts: number): number[] => {
  const hours = Math.floor(ts / 60);
  const minutes = ts % 60;
  return [hours,minutes];
}

const years = ref()

const isPrev = computed(()=>{
  return nowDate.value == new Date(`${years.value?.[0]?.value}-01-01 00:00:00`).getTime()
})

const isNext = computed(()=>{
  return nowDate.value == new Date(`${years.value?.[years.value.length - 1]?.value}-12-31 00:00:00`).getTime()
})
</script>

<template>
  <div class="ml-[39px] mr-[47px]">
    <div class="mt-[19px]">
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <img class="w-[16px] h-[16px]" src="@/assets/img/icon/5.png" alt="">
          <span class="text-[14px] text-[#4D4D4D] ml-[4px] font-medium">睡眠时间({{  timeFormat(nowDate-86400000,'mm.dd')  }}-{{ timeFormat(nowDate,'mm.dd') }})</span>
        </div>
        <div class="flex items-center">
          <div class="flex items-center mr-[8px]">
            <img v-if="isPrev" class="w-[16px] h-[16px] mr-[4px] cursor-not-allowed" src="@/assets/img/icon/28.png" alt=""/>
            <img v-else class="w-[16px] h-[16px] cursor-pointer mr-[4px]" src="@/assets/img/icon/10.png" alt="" @click="nowDate -= 86400000"/>
            <div class="w-[100px] h-[24px] time-bg flex items-center justify-center text-[12px] text-[#1A1A1A]" :class="{
              'text-[#FB2D19]': nowDate != getTodayStartTimestamp() - 86400000
            }">
              {{ timeFormat(nowDate, 'yyyy-mm-dd') }}</div>
            <img v-if="isNext" class="w-[16px] h-[16px] cursor-not-allowed ml-[4px]" src="@/assets/img/icon/27.png" alt=""/>
            <img v-else class="w-[16px] h-[16px] cursor-pointer ml-[4px]" src="@/assets/img/icon/9.png" alt="" @click="nowDate += 86400000"/>
          </div>
          <el-popover :width="352" trigger="click" :visible="visible">
            <template #reference>
              <img class="w-[24px] h-[24px] cursor-pointer" src="@/assets/img/icon/8.png" alt="" @click="visible = !visible">
            </template>
            <DateTimePicker v-model:years="years" v-model="nowDate"/>
          </el-popover>
        </div>
      </div>
    </div>
    <div class="mt-[10px] flex items-center">
      <div>
        <v-chart class="chart" :option="option" v-if="JSON.stringify(option) != '{}'" />
      </div>
      <div class="text-[#1A1A1A] text-[12px] ml-[17px]">
        <div class="flex items-center mb-[8px]">
          <div class="w-[80px] h-[49px] flex flex-col justify-center items-center bg1 mr-[8px]">
            <div>上床</div>
            <div class="text-[#FB2D19] text-[16px] font-medium">{{ data.goToBedTime }}</div>
          </div>
          <div class="w-[80px] h-[49px] flex flex-col justify-center items-center bg2">
            <div>入睡</div>
            <div class="text-[#FB2D19] text-[16px] font-medium">{{ data.sleepTime }}</div>
          </div>
        </div>
        <div class="flex items-center">
          <div class="w-[80px] h-[49px] flex flex-col justify-center items-center bg3 mr-[8px]">
            <div class="text-[#FB2D19] text-[16px] font-medium">{{ data.wakeTime }}</div>
            <div>醒来</div>
          </div>
          <div class="w-[80px] h-[49px] flex flex-col justify-center items-center bg4">
            <div class="text-[#FB2D19] text-[16px] font-medium">{{ data.getupTime }}</div>
            <div>起床</div>
          </div>
        </div>
      </div>
    </div>
    <div class="mt-[15px]">
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <img class="w-[16px] h-[16px]" src="@/assets/img/icon/5.png" alt="">
          <span class="text-[14px] text-[#4D4D4D] ml-[4px] font-medium">睡眠分析</span>
        </div>
        <div v-if="data.sleepScore <= 60" class="flex items-center justify-center text-[#808080] text-[12px] relative w-[72px] h-[24px]">
          <img class="w-[100%] h-[100%] absolute top-0 left-0" src="@/assets/img/icon/24.png" alt="">
          睡眠较差
        </div>
        <div v-else-if="data.sleepScore < 80" class="flex items-center justify-center text-[#808080] text-[12px] relative w-[72px] h-[24px]">
          <img class="w-[100%] h-[100%] absolute top-0 left-0" src="@/assets/img/icon/15.png" alt="">
          睡眠一般
        </div>
        <div v-else class="flex items-center justify-center text-[#09CDD5] text-[12px] relative w-[72px] h-[24px]">
          <img class="w-[100%] h-[100%] absolute top-0 left-0" src="@/assets/img/icon/25.png" alt="">
          睡眠良好
        </div>
      </div>
    </div>
    <div class="flex">
      <v-chart class="smfx-chart" autoresize :option="smfxOption" />
      <div class="flex items-center justify-center ml-[42px]">
        <div class="flex flex-col justify-center items-center">
          <img class="w-[40px] h-[40px]" src="@/assets/img/icon/17.png">
          <div class="text-[12px] text-[#808080]">睡眠总时长</div>
          <div class="text-[18px] text-[#1A1A1A] font-medium flex">
            {{minutesToHoursAndMinutes(data.asleepDuration || 0)[0]}}<span class="text-[12px] mt-[6px]">小时</span>{{minutesToHoursAndMinutes(data.asleepDuration || 0)[1]}}<span class="text-[12px] mt-[6px]">分</span></div>
        </div>
        <div class="flex flex-col justify-center items-center ml-[16px] mr-[16px]">
          <img class="w-[40px] h-[40px]" src="@/assets/img/icon/18.png">
          <div class="text-[12px] text-[#808080]">深睡时长</div>
          <div class="text-[18px] text-[#1A1A1A] font-medium flex">
            {{minutesToHoursAndMinutes(data.deepSleepDuration || 0)[0]}}<span class="text-[12px] mt-[6px]">小时</span>{{minutesToHoursAndMinutes(data.deepSleepDuration || 0)[1]}}<span class="text-[12px] mt-[6px]">分</span></div>
        </div>
        <div class="flex flex-col justify-center items-center">
          <img class="w-[40px] h-[40px]" src="@/assets/img/icon/16.png">
          <div class="text-[12px] text-[#808080]">离床次数</div>
          <div class="text-[18px] text-[#1A1A1A] font-medium flex">{{ data.ambulationNum || 0 }}<span class="text-[12px] mt-[6px]">次</span></div>
        </div>
      </div>
    </div>
    <div class="w-[452px] h-[72px] smjy-bg mt-[17px] ml-[8px]">
      <div class="flex items-center">
        <img class="w-[22px] h-[22px]" src="@/assets/img/icon/19.png">
        <div class="text-[14px] text-[#4D4D4D] font-medium">睡眠建议</div>
      </div>
      <div class="h-[40px] px-[8px] mt-[3px] overflow-auto">
        <vue3-auto-scroll :speed="0.1" :backSpeed="200">
          <div class="text-[12px] text-[#1A1A1A] whitespace-pre-wrap">
            充足的睡眠可以帮助维持身心健康,提高研究和工作效率。为了缓解浅睡眠过多、深睡眠不足的情况，助你提升睡眠质量，以下分享几条睡眠方面的建议:<br/>
            1、运动助眠：瑜伽运动可以通过呼吸控制、冥想、体式练习、休息术引导帮助练习者来稳定植物神经系统，按摩内脏器官，刺激腺体正常分泌激素，改善了大脑机能和身体整体机能，进而改善睡眠。<br/>
            2、饮食调理：睡前喝燕麦片和小米熬煮的稀粥，可以促进产生褪黑素促进睡眠。<br/>
            3、睡眠环境改善：调整灯光亮度。选择合适的灯光亮度可以帮助我们更好地进入睡眠状态，也可以提高睡眠质量。
          </div>
        </vue3-auto-scroll>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.time-bg{
  background: url("@/assets/img/icon/6.png") 0 0/100% 100% no-repeat;
}

.smjy-bg{
  background: url("@/assets/img/icon/14.png") 0 0/100% 100% no-repeat;
}
.chart{
  width: 275px;
  height: 148px;
}

.smfx-chart{
  width: 200px;
  height: 104px;
}

.bg1{
  background: url("@/assets/img/icon/12.png") 0 0 /100% 100% no-repeat;
}

.bg2{
  background: url("@/assets/img/icon/13.png") 0 0 /100% 100% no-repeat;
}

.bg3{
  background: url("@/assets/img/icon/11.png") 0 0 /100% 100% no-repeat;
}

.bg4{
  background: url("@/assets/img/icon/7.png") 0 0 /100% 100% no-repeat;
}

:deep(.el-popover){
  --el-popover-padding:0
}
</style>
